/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultarUsuários.java
 *
 * Created on 02/05/2011, 00:09:01
 */
package Interface;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import ludi.Usuario;
import utils.BancoDeDados;

/**
 *
 * @author alison
 */
public class ConsultarUsuarios extends javax.swing.JInternalFrame {

    BancoDeDados banco;
    Usuario usuario;

    public ConsultarUsuarios(BancoDeDados banco, Usuario usuario) {
        this.banco = banco;
        this.usuario = usuario;
        initComponents();
        setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTabelaUsuarios = new javax.swing.JScrollPane();
        tabelaUsuarios = new javax.swing.JTable();
        botaoGerenciar = new javax.swing.JButton();
        botaoCancelar = new javax.swing.JButton();
        campoBusca = new javax.swing.JTextField();
        botaoBusca = new javax.swing.JButton();
        seletorBusca = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setTitle("Consultar Usuários");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        tabelaUsuarios.setAutoCreateRowSorter(true);
        ArrayList<String> listaDeUsuarios;
        try {
            listaDeUsuarios = banco.getListaDeUsuarios(null, null);
        } catch (SQLException e) {
            e.printStackTrace();
            listaDeUsuarios = null;
        }
        tabelaUsuarios.setBackground(new java.awt.Color(254, 254, 254));
        tabelaUsuarios.setModel(modeloTabelaUsuarios(listaDeUsuarios));
        tabelaUsuarios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        scrollTabelaUsuarios.setViewportView(tabelaUsuarios);

        botaoGerenciar.setText("Gerenciar Usuário Selecionado");
        botaoGerenciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoGerenciarActionPerformed(evt);
            }
        });

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarActionPerformed(evt);
            }
        });

        campoBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoBuscaActionPerformed(evt);
            }
        });

        botaoBusca.setText("Pesquisar");
        botaoBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoBuscaActionPerformed(evt);
            }
        });

        seletorBusca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Login", "Nome", "E-mail" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(333, 333, 333)
                        .addComponent(botaoCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoGerenciar))
                    .addComponent(scrollTabelaUsuarios, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(seletorBusca, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoBusca)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(botaoBusca)
                        .addComponent(seletorBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollTabelaUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoCancelar)
                    .addComponent(botaoGerenciar))
                .addGap(15, 15, 15))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoCancelarActionPerformed

    private void botaoGerenciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoGerenciarActionPerformed
        
        if (tabelaUsuarios.getSelectedRow() < 0){
            JOptionPane.showMessageDialog(this, "Selecione um usuário!", "Consultar Usuários", JOptionPane.INFORMATION_MESSAGE);
        } else {
            String coluna;
            int i = -1;
            do {
                i++;
                coluna = tabelaUsuarios.getColumnName(i);
            } while (!(coluna.equals("Login")));

           CriarUsuario frame;
            try {
                frame = new CriarUsuario(banco, usuario, banco.getUsuario(tabelaUsuarios.getValueAt(tabelaUsuarios.getSelectedRow(), i).toString()));
                frame.setVisible(true);
                this.getDesktopPane().add(frame);
                try {
                    frame.setSelected(true);
                } catch (java.beans.PropertyVetoException e) {}
            } catch (SQLException ex) {
                Logger.getLogger(ConsultarUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_botaoGerenciarActionPerformed

    private void botaoBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBuscaActionPerformed
        busca();
    }//GEN-LAST:event_botaoBuscaActionPerformed

    private void busca(){
        ArrayList<String> listaDeUsuarios;
        try {
            if (seletorBusca.getSelectedItem().equals("Login")){
                tabelaUsuarios.setModel(modeloTabelaUsuarios(banco.getListaDeUsuarios(campoBusca.getText(), "login")));
           } else{
                if(seletorBusca.getSelectedItem().equals("Nome")){
                   tabelaUsuarios.setModel(modeloTabelaUsuarios(banco.getListaDeUsuarios(campoBusca.getText(), "nome")));
                } else{
                    tabelaUsuarios.setModel(modeloTabelaUsuarios(banco.getListaDeUsuarios(campoBusca.getText(), "email")));;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated
        ArrayList<String> listaDeUsuarios;
        try {
            listaDeUsuarios = banco.getListaDeUsuarios(null, null);
        } catch (SQLException e) {
            e.printStackTrace();
            listaDeUsuarios = null;
        }
        tabelaUsuarios.setModel(modeloTabelaUsuarios(listaDeUsuarios));
    }//GEN-LAST:event_formInternalFrameActivated

    private void campoBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoBuscaActionPerformed
        busca();
    }//GEN-LAST:event_campoBuscaActionPerformed

    private DefaultTableModel modeloTabelaUsuarios(ArrayList<String> listaDeUsuarios){
        String[][] dados = new String [0][];
        String[] colunas = new String [] {"Login", "Nome", "E-mail", "Unidade", "Tipo"};
        
        DefaultTableModel modelo = new DefaultTableModel(dados, colunas){
             Class[] types = new Class [] {
                 java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
             };
             boolean[] canEdit = new boolean [] {
                 false, false, false, false, false
             };

             @Override
             public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
             }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };

        for (int i = 0; i < listaDeUsuarios.size(); i++){
              Usuario usuario;
              try {
                   usuario = banco.getUsuario(listaDeUsuarios.get(i));
                   if (usuario.getPermissoes() == 2){
                        String unidade;
                           unidade = banco.getCurso(listaDeUsuarios.get(i)).getUnidade();
                           modelo.addRow(new Object [] {usuario.getLogin(),usuario.getNome(),usuario.getEmail(), unidade, "Curso"});
                   } else{
                       modelo.addRow(new Object [] {usuario.getLogin(),usuario.getNome(),usuario.getEmail(), "-", "Administrador"});
                   }
               }catch (SQLException ex) {
                   Logger.getLogger(CriarTime.class.getName()).log(Level.SEVERE, null, ex);
               }
         }
        return modelo;
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoBusca;
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JButton botaoGerenciar;
    private javax.swing.JTextField campoBusca;
    private javax.swing.JScrollPane scrollTabelaUsuarios;
    private javax.swing.JComboBox seletorBusca;
    private javax.swing.JTable tabelaUsuarios;
    // End of variables declaration//GEN-END:variables
}
